package com.cn.delan.web.mvc.admin.action;


import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.cn.delan.core.util.StringUtil;
import com.cn.delan.web.mvc.admin.AdminConst;
import com.cn.delan.web.mvc.admin.bean.UserBean;
import com.cn.delan.web.mvc.admin.service.IUserService;
import com.cn.delan.web.mvc.core.action.AbstractAction;
/**
 * 文件上传
 * @author BingGo
 *
 */
public class UploadAction extends AbstractAction {

	@Override
	public ModelAndView handle(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		//没有上传文件
		if(!ServletFileUpload.isMultipartContent(request)){
			return this.getView(INPUT);
		}
		//上传提示信息头
		request.setAttribute(AdminConst.REQUEST_ATTR_TITLE, this.getMessage(AdminConst.MESSAGE_UPLOAD));
		//当前目录路径
		String path = this.getParameter("path");
		File uploadDir = new File(path);
		if(!uploadDir.exists()){
			//目录不存在时,创建目录
			uploadDir.mkdirs();
		}
		//检查目录是否存在
		if(!uploadDir.isDirectory()){
			request.setAttribute(AdminConst.REQUEST_ATTR_MESSAGE, this.getMessage(AdminConst.MESSAGE_UPLOAD_NOTEXISTS));
			return this.getView(INPUT);
		}
		//检查目录写权限
		if(!uploadDir.canWrite()){
			request.setAttribute(AdminConst.REQUEST_ATTR_MESSAGE, this.getMessage(AdminConst.MESSAGE_UPLOAD_NOWRITE));
			return this.getView(INPUT);
		}
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		List items = upload.parseRequest(request);
		Iterator itr = items.iterator();
		while (itr.hasNext()) {
			FileItem item = (FileItem) itr.next();
			if (!item.isFormField()){
				String fileName = item.getName();
				try{
					File uploadFile = new File(uploadDir, fileName);
					//文件已存在
					if(uploadFile.exists()){
						request.setAttribute(AdminConst.REQUEST_ATTR_MESSAGE, this.getMessage(AdminConst.MESSAGE_FILE_EXISTS));
						return this.getView(INPUT);
					}
					item.write(uploadFile);
				}catch(Exception e){
					//上传报错
					request.setAttribute(AdminConst.REQUEST_ATTR_MESSAGE, e.getMessage());
					return this.getView(INPUT);
				}
			}
		}
		request.setAttribute(AdminConst.REQUEST_ATTR_MESSAGE, this.getMessage(AdminConst.MESSAGE_UPLOAD_SUCCESS));
		return this.getView(INPUT);
	}

}
